package com.example.yupao_project.component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.yupao_project.entity.User;
import com.example.yupao_project.exception.BusinessException;
import com.example.yupao_project.mapper.UserMapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.UUID;

/**加密、解密
 * @author: 杰
 * @date: 2024/4/30 16:28
 */
@Component
public class PasswordUtil {
    @Resource
    private UserMapper userMapper;
    /**
     * 加密
     * @param userPassword 密码
     * @return 盐值+加密后的密码（'$'分割）
     */
    public  String encrypt(String userPassword) {
        //生成盐值,并将去掉
        String salt = UUID.randomUUID().toString().replace("-","");
        //将salt和盐值合并，并进行MD5加密
        String encryptPassword = DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());
        return salt + "$" + encryptPassword;
    }

    /**
     * 解密
     * @param userPassword 密码
     * @return true / false
     */
    public User decrypt(String userAccount, String userPassword) {
        //1.校验参数
        if (!StringUtils.hasLength(userAccount))
            throw new BusinessException(ErrorCode.NULL_ERROR,"账号为空");
        if (!StringUtils.hasLength(userPassword))
            throw new BusinessException(ErrorCode.NULL_ERROR,"密码为空");
        //2.查询数据
        //获取数据库数据
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount",userAccount);
        User eqUser = userMapper.selectOne(queryWrapper);
        if (eqUser == null || eqUser.getUserPassword().isEmpty()) return null;
        String encryptData = eqUser.getUserPassword();
        //分解盐值和加密后的密码
        String[] data = encryptData.split("\\$");
        //将盐值和userPassword结合加密得到密码
        String encryptPassword = DigestUtils.md5DigestAsHex((data[0] + userPassword).getBytes());
        //判断两个密码是否相同
        if (encryptPassword.equals(data[1])) {
            return eqUser;
        }
        return null;
    }
}
